#!/bin/bash
# sed -i 's/\r//' file.txt
# 这个命令会删除文件 file.txt 中的所有回车符（\r），从而将 CRLF 转换为 LF。
# 如果工具包没有安装，请先安装sudo apt update && sudo apt install cloud-guest-utils

# 检测root
if ! [ $(id -u) = 0 ]; then
  echo "Please run as root"
  exit 1
fi
# 检测工具包
if ! [ -x "$(command -v growpart)" ]; then
  echo "growpart not found, please install cloud-guest-utils"
  echo "sudo apt update && sudo apt install cloud-guest-utils"
  exit 1
fi
ROOT_DEV=$(findmnt -n -o SOURCE /)
DEVICE_NAME=${ROOT_DEV%p*}
PART_NUM=${ROOT_DEV##*p}


if growpart $DEVICE_NAME $PART_NUM ; then
  case $(blkid -s TYPE -o value $ROOT_DEV) in
    ext4)  resize2fs $ROOT_DEV ;;
    xfs)   xfs_growfs / ;;
    btrfs) btrfs filesystem resize max / ;;
    *)     echo "Unsupported FS: $(blkid -s TYPE -o value $ROOT_DEV)" >&2; exit 1 ;;
  esac
fi